﻿using System;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using CSW.Framework.Common;
using CSW.Framework.Common.Binding;
using CSW.Framework.Linq.QueryModel;
using CSW.Framework.Linq.SchemaModel;

namespace CSW.Framework.Linq
{
    /// <summary>
    /// A LINQ enabled <see cref="BusinessObject"/>.
    /// </summary>
    public abstract partial class BusinessObjectLinqBase<T> : BusinessObject, IBusinessObjectLinq, IBusinessObjectLinqPublic
        where T : IDatabase, new()
    {
        /// <summary>
        /// IsNew (not loaded from database) indicator. Use SetIsNew method to have PropertyChanged event fire.
        /// </summary>
        protected bool m_IsNew = true;

        private MethodInfo m_IdentitySetter;
        private Table m_Table;
        private readonly object m_TableLocker = new object();
        private bool m_PropertiesInitialized;
        private readonly object m_PropertiesInitializedLocker = new object();

        /*/// <summary>
        /// Initializes a new instance of the <see cref="BusinessObjectLinqBase&lt;T&gt;"/> class.
        /// </summary>
        protected BusinessObjectLinqBase()
        {
            ObjectCounter.Add(this);
        }*/

        /// <summary>
        /// Gets the <see cref="Property"/> of a given expression.
        /// </summary>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="property">The property.</param>
        /// <returns>The <see cref="Property"/>.</returns>
        public Property<TResult> GetProperty<TSource, TResult>(Expression<Func<TSource, TResult>> property)
        {
            Guard.ArgumentNotNull(property, "property");

            string fieldName = LinqToSqlHelper.GetFieldName(property);
            return (Property<TResult>)Properties[fieldName];
        }

        /// <summary>
        /// Populates the child binding list.
        /// </summary>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="field">The field.</param>
        /// <param name="bindingList">The binding list.</param>
        public void PopulateChildBindingList<TSource, TEntity>(Expression<Func<TSource, BindingList<TEntity>>> field, BindingList<TEntity> bindingList)
            where TSource : class, IBusinessObjectLinq
            where TEntity : class, IBusinessObjectLinq
        {
            Guard.ArgumentNotNull(field, "field");
            Guard.ArgumentNotNull(bindingList, "bindingList");

            // TODO: this method needs to be tested

            TSource arg = this as TSource;
            Debug.Assert(arg != null);

            BindingList<TEntity> entitySet = field.Compile()(arg);

            string[] strArray = field.ToString().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            string propertyName = strArray[strArray.Length - 1];
            if (bindingList.Count != 0)
                throw new ArgumentException("bindingList is not empty.", "bindingList");

            foreach (TEntity local2 in entitySet)
            {
                bindingList.Add(local2);
            }

            // swap is intentional.. 
            Properties[propertyName].UnsafeValue = bindingList;
            //PopulateInitialValues(info);
        }

        void IBusinessObjectLinq.LoadFromDataRow(Query dynamicQuery, DataRow dataRow)
        {
            LoadFromDataRow(this, dynamicQuery, dataRow);
        }

        void IBusinessObjectLinq.LoadFromDataRowCompiled(Query dynamicQuery, DataRow dataRow)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Sets the Is New indicator.
        /// </summary>
        /// <param name="isNew">if set to <c>true</c> the record is new, not loaded from the database; otherwise, use <c>false</c>.</param>
        protected void SetIsNew(bool isNew)
        {
            m_IsNew = isNew;
            SendPropertyChanged("IsNew");
        }

        internal void SetIdentity(int identity)
        {
            if (m_IdentitySetter == null)
            {
                GetTable();
                if (m_IdentitySetter == null)
                {
                    throw new Exception("No identity setter set.");
                }
            }

            BeginLoading();
            try
            {
                m_IdentitySetter.Invoke(this, new object[] { identity });
            }
            finally
            {
                EndLoading();
            }
        }

        /// <summary>
        /// Gets the table representing the current object in a thread-safe manner.
        /// </summary>
        /// <returns>The table representing the current object.</returns>
        protected Table GetTable()
        {
            if (m_Table == null)
            {
                lock (m_TableLocker)
                {
                    if (m_Table == null)
                    {
                        m_Table = m_Schema.Tables.Where(p => p.FullClassName == GetType().FullName).Single();

                        TableColumn identityColumn = m_Table.Columns.Where(p => p.IsIdentity).SingleOrDefault();
                        if (identityColumn != null)
                        {
                            TableProperty tableProperty = m_Table.Properties.Where(p => p.Column == identityColumn).Single();
                            m_IdentitySetter = GetPropertySetterDictionary(GetType(), m_Table)[tableProperty.PropertyName];
                        }
                    }
                }
            }

            return m_Table;
        }

        /// <summary>
        /// Gets a value indicating whether this table has computed columns.
        /// </summary>
        /// <value><c>true</c> if this instance has computed columns; otherwise, <c>false</c>.</value>
        public abstract bool HasComputedColumns { get; }

        bool IBusinessObjectLinqPublic.m_IsNew
        {
            get { return m_IsNew; }
            set { m_IsNew = value; }
        }

        void IBusinessObjectLinqPublic.BeginLoading()
        {
            BeginLoading();
        }

        void IBusinessObjectLinqPublic.EndLoading()
        {
            EndLoading();
        }

        bool IBusinessObjectLinqPublic.PropertiesInitialized
        {
            get { return PropertiesInitialized; }
        }

        private bool m_IsDisposed;

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="BusinessObjectLinq&lt;T&gt;"/> is reclaimed by garbage collection.
        /// </summary>
        ~BusinessObjectLinqBase()
        {
            //ObjectCounter.Remove(this);
            Dispose();
        }

        private void Dispose()
        {
            if (m_IsDisposed)
                return;

            if (m_DynamicQuery != null)
            {
                m_DynamicQuery.Users -= 1;
                if (m_DynamicQuery.Users == 0)
                {
                    LoadVariables<T>.Remove(m_DynamicQuery);
                }
            }

            m_IsDisposed = true;
        }

        private Query m_DynamicQuery;
        internal Query DynamicQuery
        {
            get { return m_DynamicQuery; }
            set
            {
                if (m_DynamicQuery == null)
                {
                    m_DynamicQuery = value;
                    m_DynamicQuery.Users += 1;
                }
                else if (m_DynamicQuery != value)
                {
                    m_DynamicQuery.Users -= 1;
                    if (m_DynamicQuery.Users == 0)
                    {
                        LoadVariables<T>.Remove(m_DynamicQuery);
                    }

                    m_DynamicQuery = value;
                    m_DynamicQuery.Users += 1;
                }
            }
        }

        /// <summary>
        /// Determines whether the object is new (not saved to the database).
        /// </summary>
        /// <value></value>
        /// <returns><c>true</c> if this instance is new; otherwise, <c>false</c>.</returns>
        public override bool IsNew
        {
            get { return m_IsNew; }
        }

        /// <summary>
        /// Gets the PropertiesInitialized locker.
        /// </summary>
        /// <value>The PropertiesInitialized locker.</value>
        protected object PropertiesInitializedLocker
        {
            get { return m_PropertiesInitializedLocker; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether the object's properties are initialized.
        /// </summary>
        /// <value><c>true</c> if the properties are initialized; otherwise, <c>false</c>.</value>
        protected bool PropertiesInitialized
        {
            get
            {
                lock (m_PropertiesInitializedLocker)
                {
                    return m_PropertiesInitialized;
                }
            }
            set
            {
                lock (m_PropertiesInitializedLocker)
                {
                    if (PropertiesInitialized != value)
                        m_PropertiesInitialized = value;
                }
            }
        }

        /// <summary>
        /// Throws an exception if the object is not edittable.
        /// </summary>
        protected override void CheckEdittable()
        {
            if (!IsLoading && !IsEditting)
                BeginEdit(false);
        }
    }
}
